package com.liujit.gateway.service;

import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ReactiveHashOperations;
import org.springframework.data.redis.core.ReactiveRedisTemplate;
import org.springframework.data.redis.core.ReactiveValueOperations;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.Duration;
import java.util.Map;
import java.util.Optional;

/**
 * @Description: Redis
 * @Author: liujun
 * @Date: 2021/6/28 1:36 下午
 */
@RequiredArgsConstructor
@Service
public class RedisService {

    private final ReactiveRedisTemplate<String, String> redisTemplate;

    /**
     * 写入缓存
     *
     * @param key
     * @param value
     * @return
     */
    public Mono<Boolean> set(final String key, String value) {
        ReactiveValueOperations<String, String> operations = redisTemplate.opsForValue();
        return operations.set(key, value);
    }

    /**
     * 重置有效期
     *
     * @param key
     * @param duration
     * @return
     * @author: liujun
     * @date: 2021/6/28 1:59 下午
     */
    public Mono<Boolean> setExpire(String key, Duration duration) {
        ReactiveValueOperations<String, String> operations = redisTemplate.opsForValue();
        return redisTemplate.expire(key, duration);
    }

    /**
     * 写入缓存
     *
     * @param key
     * @param value
     * @param duration
     * @return
     */
    public Mono<Boolean> set(final String key, String value, Duration duration) {
        ReactiveValueOperations<String, String> operations = redisTemplate.opsForValue();
        return operations.set(key, value, duration);
    }

    /**
     * 获取缓存
     *
     * @param key
     * @return
     */
    public Mono<String> get(String key) {
        ReactiveValueOperations<String, String> operations = redisTemplate.opsForValue();
        return operations.get(key);
    }

    /**
     * 判断缓存中是否有对应的value
     *
     * @param key
     * @return
     */
    public Mono exists(final String key) {
        return redisTemplate.hasKey(key);
    }

    /**
     * 哈希获取数据
     *
     * @param key
     * @return
     */
    public Flux<Map.Entry<Object, Object>> hmGet(String key) {
        ReactiveHashOperations<String, Object, Object> operations = redisTemplate.opsForHash();
        return operations.entries(key);
    }
}
